package com.lichuan.zhaoshangdemo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * CORS 全局跨域配置
 */
@Slf4j
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();

        // ✅ 推荐用 addAllowedOriginPattern 替代 addAllowedOrigin
        config.addAllowedOriginPattern("http://localhost:5173");

        config.setAllowCredentials(true);          // 允许携带 cookie/token
        config.addAllowedHeader("*");              // 允许所有请求头
        config.addAllowedMethod("*");              // 允许所有方法
        config.addExposedHeader("Content-Type");   // 可选暴露响应头
        config.setMaxAge(3600L);                   // 预检请求缓存时间

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        return new CorsFilter(source);
    }
}
